import axios from 'axios'
import local from './local'
import { machineId } from 'node-machine-id'
import md5 from 'js-md5'

// axios基础配置
const service = axios.create({
    baseURL: 'http://149.28.95.247:39876/appapi',
    timeout: 10000,
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }

})
// let a;
// 异或加密
function xor(str) {
    var key = "Ylnflsd!Xa?ak09";
    var sb = '';
    // 异或算法
    for (var i = 0; i < str.length; i++) {
        sb += String.fromCharCode(str.charCodeAt(i) ^ key.charCodeAt(i % key.length));
    }
    // a = sb
    return sb;
}

// 请求拦截器
service.interceptors.request.use(async (config) => {
    let data = {}
    if (config.data) {
        // 取到接口传过来的值
        console.log(data);
        data = config.data.data
    }
    const formData = {}
    // 添加公共参数
    data.version = '1.0.0'
    data.platform = 'pc'
    // id太长则md加密
    data.deviceid = md5(await machineId())
    const token = local.localGet("token")
    // console.log(token);
    if (token && token != 'undefined') {
        // data.token = token.substring(1, token.length - 1)
        data.token = JSON.parse(token)
    }
    // console.log(data, "data__________");
    formData.data = xor(JSON.stringify(data))
    config.data = formData
    // console.log(xor(a), 'aaaaaaaaaaaaaaaa');
    return config
}, function (err) {
    return Promise.reject(err)
})


service.interceptors.response.use((response) => {
    response.data = JSON.parse(xor(response.data))
    if (String(response.data.code) === '2' && response.data.data === 'token_err') {
        local.remove('token')
        window.location.href = "#/login"
    }
    return response
}, function (err) {
    return Promise.reject(err)
})

export default service